const { getPayloadByToken } = require("./jwt");
const { db } = require("./database");

const GenerateAuthMiddle = (name) => {
  return async (req, res, next) => {
    // 从请求头部获得 token
    const { token } = req.headers;
    const payload = getPayloadByToken(token);
    // 获取用户id
    const userId = payload?.userId || req.session?.userId;
    // 通过 session.userId 判断用户是否登录
    if (!userId) {
      return res.status(401).send({ success: false, message: "用户尚未登录!" });
    }
    // 为以后获取用户信息方便，将用户信息保存在 req.user 上。
    req.user = await db.findOne(`select * from ${name} where id = ?`, [userId]);
    next();
  };
};

const ManagerAuth = GenerateAuthMiddle("manager"),
  CustomerAuth = GenerateAuthMiddle("customer");

module.exports = { ManagerAuth, CustomerAuth };
